<script setup>
import {reactive, ref, onMounted} from 'vue'
import Dialog from '@/components/admin/EditDialog.vue'
import {ElMessage} from "element-plus";
import {
  GetAllPetMessageService,
  AddPetMessageService,
  deleteNetShopPetMessageService
} from '@/api/netshop/establish.js'

const size = ref('')
const data = ref([])
const loading = ref(true)

const getList = async () => {
  const username = JSON.parse(localStorage.getItem('custom')).custom_username
  console.log(username)
  await GetAllPetMessageService(username)
      .then((res) => {
        console.log(res)
        data.value = res.data.data
        loading.value = false
        // console.log(res.data.results.data)
      })
      .catch((err) => {
        console.log(err)
      })
}
onMounted(() => {
  getList()
})
// 对话框展开
const dialogObject = reactive({
  dialogVisible: false,
  title: '',
  width: '700',
  successBtnText: '确定',
  closeBtnText: '取消',
  isFooter: true
})
// 上架对话框
const addClick = () => {
  dialogObject.dialogVisible = true
  console.log(dialogObject.dialogVisible)
  dialogObject.title = '建档'
}
// 对话框数据绑定
const form = ref({})

// 对话框
const formfields = ref({
  base: [
    {
      label: '宠物名字', field: 'petname',
      rules: [
        {required: true, message: '宠物花名需要填写', trigger: 'blur'}
      ]
    },
    {
      label: '性别', field: 'petsex', type: 'select',
      options: {
        data: [{label: '雄性', value: 1}, {label: '雌性', value: 2}]
      },
      rules: [
        {required: true, message: '请选择性别', trigger: 'blur'}
      ]
    },
    {
      label: '宠物种类', field: 'petcatagory', type: 'select',
      options: {
        data: [{label: '狗', value: '狗'}, {label: '猫', value: '猫'}]
      },
      rules: [
        {required: true, message: '请选择品种', trigger: 'blur'}
      ]
    },
    {
      label: '宠物种类', field: 'petkind',
      rules: [
        {required: true, message: '宠物种类需要填写', trigger: 'blur'}
      ]
    },
    {
      label: '宠物年龄', field: 'petage',
      rules: [
        {required: true, message: '宠物年龄需要填写', trigger: 'blur'}
      ]
    },
    {
      label: '疫苗注射情况', field: 'petvaccines', type: 'select',
      options: {
        data: [{label: '已接种', value: 1}, {label: '未接种', value: 2}]
      },
      rules: [
        {required: true, message: '请选择性别', trigger: 'blur'}
      ]
    },
    {
      label: '健康程度', field: 'healthy', type: 'select',
      options: {
        data: [
          {label: '健康', value: 1},
          {label: '少许疾病', value: 2},
          {label: '重大疾病', value: 3},
          {label: '残疾', value: 4},
          {label: '其他', value: 5},
        ]
      },
      rules: [
        {required: true, message: '请选择健康程度', trigger: 'blur'}
      ]
    },
    {
      label: '上次接种时间', field: 'petvaccinestime', type: 'date',
      rules: [{required: true, message: '选择上架时间'}]
    },
    {
      label: '上传图片', field: 'imagesurl', type: 'pic'
    },
    {
      label: '详细描述', field: 'description'
    },
  ],
})

// 图片上传的token
const uploadHeaders = ref({
  Authorization: 'bearer' + ' ' + localStorage.getItem('custom_token')
})

// 上传前的图片校验
const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== "image/jpg" && rawFile.type !== "image/png" && rawFile.type !== "image/jpeg") {
    console.log(rawFile)
    ElMessage.error('文件格式必须是jpg、jpeg或者png')
    return false
  } else if (rawFile.size / 1024 / 1024 > 20) {
    ElMessage.error('该文件格式不能超过 20MB!')
    return false
  }
  return true
}

// 图片先上传回服务器然后再将图片本地的地址返回来，再走drf将图片存放本地的路径存到数据库
const handleAvatarSuccess = async (response, file) => {
  form.value.imagesurl = response['0']
  console.log('图片的地址', form.value.imagesurl)
}
// 提交表单增加数据
const handleFormSubmit = async (form) => {
  const username = JSON.parse(localStorage.getItem('custom')).custom_username
  await AddPetMessageService(form, username)
      .then((res) => {
        // console.log(res)
        dialogObject.dialogVisible = false
        getList()
      })
      .catch((error) => {
        console.log(error)
      })
}

// 删除
const Delete = async (id) => {
  await deleteNetShopPetMessageService(id)
      .then((res) => {
        // console.log(res)
        dialogObject.dialogVisible = false
        getList()
      })
      .catch((error) => {
        console.log(error)
      })
}
</script>

<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <span>
          档案列表
          <el-tooltip
              effect="dark"
              content="如需修改档案，请删除档案并重新建立"
              placement="top"
          >
          <el-icon style="margin-left: 4px" :size="12">
            <Warning/>
          </el-icon>
        </el-tooltip>
        </span>

        <el-button class="button" @click="addClick" text>新增</el-button>
      </div>
    </template>
    <div v-loading="loading" style="overflow: auto;height: 740px">
      <el-empty v-if="data.length === 0" description="当前没有您的宠物档案，新建一个憋！！！"/>
      <el-row v-else v-for="item in data" :key="item.id">
        <el-col :span="24">
          <el-card class="box-card" shadow="always">
            <template #header>
              <div class="card-header">
                <span>宠物档案</span>
              </div>
            </template>
            <el-descriptions
                direction="vertical"
                :column="4"
                :size="size"
                border
            >
              <el-descriptions-item label="宠物名">{{ item.petname }}</el-descriptions-item>
              <el-descriptions-item label="宠物年龄">{{ item.petage }}年</el-descriptions-item>
              <el-descriptions-item label="宠物品种">{{ item.petkind }}</el-descriptions-item>
              <el-descriptions-item label="宠物种类">{{ item.petcatagory }}</el-descriptions-item>
              <el-descriptions-item label="性别">{{ item.petsex === 1 ? '雄性' : '雌性' }}</el-descriptions-item>
              <el-descriptions-item label="注射疫苗的情况">
                <el-tag v-if="item.petvaccines===2" type="info" size="default">未注射</el-tag>
                <el-tag v-else type="success" size="small">已注射</el-tag>
              </el-descriptions-item>
              <el-descriptions-item :span="2" label="上次注射疫苗的时间">
                {{ item.petvaccinestime }}
              </el-descriptions-item>
              <el-descriptions-item :span="1" label="健康程度">
                <el-tag v-if="item.healthy===1" type="success" size="small">健康</el-tag>
                <el-tag v-else-if="item.healthy===2" type="primary" size="small">少许疾病</el-tag>
                <el-tag v-else-if="item.healthy===3" type="warning" size="small">重大疾病</el-tag>
                <el-tag v-else-if="item.healthy===4" type="danger" size="small">残疾</el-tag>
                <el-tag v-else type="info" size="small">其他</el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="宠物照片">
                <div class="demo-image__preview">
                  <el-image
                      style="width: 200px; height: 200px"
                      :src="item.imagesurl"
                      :zoom-rate="1.2"
                      :max-scale="7"
                      :min-scale="0.2"
                      :preview-src-list="[item.imagesurl]"
                      :initial-index="4"
                      fit="cover"
                  />
                </div>
              </el-descriptions-item>
              <el-descriptions-item :span="4" label="补充说明">
                {{ item.description }}
              </el-descriptions-item>
            </el-descriptions>
            <template #footer>
              <el-popconfirm
                  confirm-button-text="是"
                  cancel-button-text="否"
                  :icon="InfoFilled"
                  icon-color="#626AEF"
                  title="是否删除档案?"
                  @confirm="Delete(item.id)"
                  @cancel="cancelEvent"
              >
                <template #reference>
                  <el-button text>删除</el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </el-card>

  <div>
    <Dialog
        :dialogobject="dialogObject"
        :formlist="formfields.base"
        :model="form"
        @submit="handleFormSubmit"
        @edit="handleFormEdit"
    >
      <template #pictures="{row}">
        <el-upload
            action="http://127.0.0.1:8000/netshop/petmessage/upload/"
            list-type="picture-card"
            :auto-upload="true"
            ref="pictureUpload"
            :headers="uploadHeaders"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :limit="3"
        >
          <el-icon>
            <Plus/>
          </el-icon>
          <template #file="{ file }">
            <div>
              <img class="el-upload-list__item-thumbnail" :src="file.url" alt=""/>
              <span class="el-upload-list__item-actions">
          <span
              class="el-upload-list__item-preview"
              @click="handlePictureCardPreview(file)"
          >
            <el-icon><zoom-in/></el-icon>
          </span>
          <span
              v-if="!disabled"
              class="el-upload-list__item-delete"
              @click="handleRemove(file)"
          >
            <el-icon><Delete/></el-icon>
          </span>
        </span>
            </div>
          </template>
        </el-upload>
        <el-dialog v-model="dialogVisible">
          <img w-full :src="form.fileList" alt="Preview Image"/>
        </el-dialog>
      </template>
    </Dialog>
  </div>

</template>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.el-row {
  margin-bottom: 20px;
}

.demo-image__error .image-slot {
  font-size: 30px;
}

.demo-image__error .image-slot .el-icon {
  font-size: 30px;
}

.demo-image__error .el-image {
  width: 100%;
  height: 200px;
}
</style>